'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  
  constructor(...props) {
    super(...props)
    //创建的规则
    const createValidateRule = { email: 'string', nickname: 'string', password: 'string', code: 'string'}
    this.createValidateRule = createValidateRule
  }
  //@POST  登入
  async vertify() {
    const { ctx, service } = this;
    const { Response, ResponseError, request: { body }, session } = ctx
    const res = new Response()
    try {
      ctx.validate({password: 'string', nickname: 'string'}, body);
      const { nickname, password } = body
      //查询是否存在用户
      let user = await service.user.findByFields({nickname})
      if(!user) {
        throw new ResponseError('用户：' + nickname + '不存在!')
      }

      if(user && user.status === '0') {
        throw new ResponseError('用户被锁定')
      }

      //验证通过，判断密码是否正确
      if(password != user.password) {
        throw new ResponseError('密码错误')
      }
      session.user_id = user.id // 存储session
      user = user.toJSON()
      user.password = undefined
      res.data = {
        user
      }
      res.message = '登入成功'
    }catch(e) {
      console.log(e.message)
			res.status = ctx.STATUS.ERROR;
			res.message = e;
    }
    ctx.body = res;
  }

  //@GET users/:user_id/booklets
  async booklets() {
    const { ctx, service } = this;
    const { Response, params, ResponseError, session } = ctx
    const res = new Response()
    try {
      const { user_id } = params
      let user = await service.user.find(user_id)
      if(!user) {
        throw new ResponseError('用户：' + nickname + '不存在!')
      }

      if(user && user.status === '0') {
        throw new ResponseError('用户被锁定')
      }

      if(session.user_id != user_id) { //令牌验证
        throw new ResponseError('用户没有登入')
      }
      const userBookletRecords = await  service.booklet.findBookletByUserId(user_id)
      const booklets = userBookletRecords.map(function(userBookletRecord) {
        return userBookletRecord.booklet_model
      })
      res.data = {
        booklets
      }
      res.message = '书籍资料获取成功'
    }catch(e) {
      console.log(e.message)
			res.status = ctx.STATUS.ERROR;
			res.message = e;
    }
    ctx.body = res;
  }
}

module.exports = UserController;
